package com.servlet;

import com.dao.UserDAO;
import com.dao.impl.UserDAOImpl;
import com.entity.User;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;


import java.io.IOException;
import java.io.PrintWriter;

/*
 *
 * @author hy
 * @dote 2024-11-28
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");

        String username = req.getParameter("username");
        String password = req.getParameter("password");

        UserDAO userDAO = new UserDAOImpl();
        PrintWriter out = resp.getWriter();

        // 检查用户是否存在
        User user = userDAO.getUserByUsername(username);

        if (user == null) {
            resp.setContentType("application/json");
            out.print("{\"success\":false, \"message\":\"用户名不存在\"}");
        } else {
//            // 验证密码
//            System.out.println(user.getPassword().length());
//            System.out.println(password.length());

            if (user.getPassword().equals(password)) {
                // 登录成功，创建会话并返回成功消息
                HttpSession session = req.getSession();
                //将uesrname保存到session中
                session.setAttribute("username", username);

                resp.setContentType("application/json");
                out.print("{\"success\":true, \"message\":\"登录成功\"}");
            } else {
                // 密码不正确
                resp.setContentType("application/json");
                out.print("{\"success\":false, \"message\":\"密码错误\"}");
            }
        }

        out.flush();
        out.close();
    }
}